package com.key.gradle.test.config;

import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.key.gradle.test.handler.CustomAsyncUncaughtExceptionHandler;

/**
 * @see https://docs.spring.io/spring/docs/current/javadoc-api/org/
 *      springframework/scheduling/annotation/EnableAsync.html
 * @see http://www.baeldung.com/spring-async
 */
@Configuration
@EnableAsync
public class SpringAsyncConfig implements AsyncConfigurer {

	@Override
	public Executor getAsyncExecutor() {
		// 只是 demo 所以各项数值设置得都比较小
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		// default is 1
		executor.setCorePoolSize(3);
		// default is Integer.MAX_VALUE
		executor.setMaxPoolSize(10);
		// 等待队列
		// default is Integer.MAX_VALUE
		executor.setQueueCapacity(10);
		executor.setThreadNamePrefix("DFT-ASYNC-EXECUTOR-");
		executor.initialize();
		return executor;
	}
	
	@Bean(name = "anotherAsyncExecutor")
    public Executor anotherAsyncExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(2);
		executor.setMaxPoolSize(5);
		executor.setQueueCapacity(5);
		executor.setThreadNamePrefix("ANOTHER-ASYNC-EXECUTOR-");
		executor.initialize();
		return executor;
    }

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new CustomAsyncUncaughtExceptionHandler();
	}

}
